import { BUS_THEME, BusDetail } from '@/apis/bus';
import Bg from '@/assets/choise-bg.jpg';
import Ice from '@/assets/render-1.png';
import ContentBg from '@/assets/render-2.png';
import SaveTip from '@/assets/render-4.png';
import ZhuanShuLabel from '@/assets/render-5.png';
import QRCodeCanvas from 'qrcode.react';
import { useQuery, useSearchParams } from 'umi';

import Title from '@/assets/render-3.png';

import { getUserInfo } from '@/apis/user';
import BusNike from '@/components/Bus/Nike';
import BusZhuDi from '@/components/Bus/Zhudi';
import { initWXConfig } from '@/utils';
import html2canvas from 'html2canvas';
import { useEffect, useMemo, useState } from 'react';

// ## 需要携带参数 busId=xx
export default function Page() {
  const [searchParams] = useSearchParams();
  const busId = searchParams?.get('busId');
  // ?车队信息
  const { data: bus } = useQuery(
    ['bus:detail:render'],
    () => BusDetail({ id: busId! }),
    {
      enabled: !!busId,
      onSuccess: function () {
        // #设置分享出去的链接
        initWXConfig({
          link: `${window.location.origin}?busId=${bus?.id}&shareUser=${bus?.user_id}`,
        });
      },
    },
  );

  // ?拿到自己的信息
  const self = useMemo(() => bus?.passengers?.[0], [bus]);
  const theme = useMemo(() => bus?.theme, [bus]);
  const { data: user } = useQuery(['user:info:render'], () => getUserInfo());
  const qrCodeValue = useMemo(
    () =>
      `${window.location.origin}?busId=${bus?.id}&shareUser=${bus?.user_id}`,
    [bus],
  );

  const [base64, setBase64] = useState<string>('');
  const [qrCodeSize, setQrCodeSize] = useState<number>(0);

  useEffect(() => {
    if (bus?.id && user?.nickname) {
      const qrCodeContainer = document.querySelector(
        '.qrCode-container',
      ) as HTMLDivElement;
      setQrCodeSize(qrCodeContainer.clientWidth || 50);

      setTimeout(() => {
        console.log('html2canvas is render ....');
        html2canvas(document.getElementById('root') as HTMLElement, {
          scale: 3,
          useCORS: true,
          backgroundColor: 'transparent',
          onclone: function (docClone) {
            const nickName = docClone.querySelector('.nickname') as HTMLElement;
            if (!nickName) return;
            nickName.style.marginTop = `-25px`;

            const uploadPlusIcons = docClone.querySelectorAll('.upload-plus');
            if (!uploadPlusIcons) return;
            for (const dom of uploadPlusIcons as any)
              dom.style.marginTop = `-20px`;
          },
        }).then(function (canvas) {
          canvas && setBase64(canvas.toDataURL());
        });
      }, 10);
    }
  }, [bus, user]);

  return (
    <>
      <section className=" min-h-screen overflow-hidden relative pt-[40px] flex items-center flex-col">
        <img
          src={Bg}
          className="absolute left-0 top-0 w-screen h-screen object-cover"
        />

        <img
          src={Ice}
          className="w-[58px] h-[72px] bg-cover block mb-4 relative"
        />

        <div className=" w-[550px] h-[911px] bg-cover pt-[80px] contentContainer relative">
          <img
            src={ContentBg}
            className=" absolute left-0 top-0 w-full h-full"
            alt=""
          />

          {base64 && (
            <img
              src={base64}
              className="w-full h-full absolute left-0 top-0 z-20 opacity-0"
              alt=""
            />
          )}

          {/* nick name */}
          <div className="flex items-center justify-center leading-none relative">
            <h1
              className="nickname text-[40px] text-[#7eff61] mr-1 leading-none"
              style={{
                textShadow: '1px 1px 1px rgba(0,0,0,.4)',
              }}
            >
              @{self?.name}
            </h1>
            <img
              src={ZhuanShuLabel}
              className="w-[calc(158px/1.5)] h-[calc(78px/1.5)] bg-cover"
            />
          </div>

          <img
            src={Title}
            className="w-[calc(446px/1.2)] h-[calc(52px/1.2)] bg-cover mx-auto mt-2 relative"
          />

          {/* bus */}
          {theme === BUS_THEME.NIKE && (
            <div className="w-[513px] -ml-[3px] overflow-hidden mt-[60px] relative">
              <div className="w-[680px]">
                <BusNike readonlyFriend readonly selfAvatar={self?.head} />
              </div>
            </div>
          )}
          {theme === BUS_THEME.ZHUDI && (
            <div className="w-[513px] -ml-[3px] overflow-hidden mt-[60px] relative">
              <div className="w-[680px]">
                <BusZhuDi readonlyFriend readonly selfAvatar={self?.head} />
              </div>
            </div>
          )}

          {/* qrcode */}
          <div className="w-[100px] h-[100px] border-4 border-white absolute right-[84px] bottom-[50px] rounded-sm qrCode-container">
            {Boolean(qrCodeSize) && (
              <QRCodeCanvas size={qrCodeSize} value={qrCodeValue} />
            )}
          </div>
        </div>

        <p
          className="w-[440px] h-[74px] bg-cover relative "
          data-html2canvas-ignore
          style={{
            backgroundImage: `url(${SaveTip})`,
          }}
        ></p>
      </section>
    </>
  );
}
